const { Controller } = require('egg');
const { validateDigest, fail, sendSms, isPhone } = require('../utils');
class HomeController extends Controller {
  async smsSend() {
    const { headers, body } = this.ctx.request;
    const validate = validateDigest(headers.appid, headers.digest);
    if(!validate) {
      return this.ctx.body = fail('Invalid digest', 401)
    }
    const { phone, content } = body
    if(!isPhone(phone)) {
      return this.ctx.body = fail('Invalid phone', 422)
    }
    if(!content) {
        return this.ctx.body = fail('Invalid content', 422)
    }
    const result = sendSms(phone, content);
    if(result.success) {
      return this.ctx.body = { success: true, message: 'OK', data: result.message };
    } else {
      return this.ctx.body = fail(result.message, 500)
    }
  }
}

module.exports = HomeController;
